package com.example.config;

import com.example.core.BusinessException;
import com.example.core.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultEntity methodDtoNotValidException(MethodArgumentNotValidException c, HttpServletRequest request) {
        List<ObjectError> errors = c.getBindingResult().getAllErrors();
        StringBuffer errorMsg = new StringBuffer();
        errors.stream().forEach(x -> {

            errorMsg.append(x.getDefaultMessage()).append(";");
        });
        return ResultEntity.STATUS_MSG("-1", errorMsg.toString());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResultEntity methodArgNotValidException(ConstraintViolationException cve, HttpServletRequest httpServletRequest) {
        Set<ConstraintViolation<?>> cves = cve.getConstraintViolations();
        StringBuffer errorMsg = new StringBuffer();
        cves.forEach(ex -> errorMsg.append(ex.getMessage()));

        return ResultEntity.STATUS_MSG("-1", errorMsg.toString());
    }

    @ExceptionHandler(value = BusinessException.class)
    public ResultEntity defaultErrorHandler(BusinessException e) {
        log.error("error code: {} ;error msg: {}", e.getCode(), e.getMessage());

        return ResultEntity.STATUS_MSG(e.getCode(), e.getMessage());

    }

    @ExceptionHandler(Exception.class)
    public ResultEntity handleException(Exception e) {
        log.error("系统运行抛出异常；异常信息*************** {}", e.getMessage());
        e.printStackTrace();
        return ResultEntity.STATUS_MSG("500", "系统繁忙,请稍后再试");
    }


}
